package Servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import DAL.Entites.Rank;
import DAL.JDBC.DBConn;
import DAL.JDBC.RankJDBC;

public class AddRank extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private RankJDBC rankJdbc;
    
    public void init()
    {
    	rankJdbc = new RankJDBC(DBConn.getConnection());
    }
    public AddRank() {
        super();
        
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		JSONObject result = new JSONObject();
		int gameId = Integer.parseInt(request.getParameter("gameId"));
		int rankNumber = Integer.parseInt(request.getParameter("rank"));
		int userID = Integer.parseInt(request.getParameter("userId"));
		//int userID = Integer.parseInt(request.getSession().getAttribute("userId"));
		
		Rank rank = rankJdbc.getRankForUserAndGame(userID, gameId);
		try {
			if(rank != null)
			{
				rank.setRankNumber(rankNumber);
				rankJdbc.update(rank);
				result.put("result", true);
				result.put("message", "Updated");
			}
			else if(rankNumber < 1 || rankNumber > 5)
			{
				result.put("result", false);
				result.put("message", "Rank Out Of Range");
			}
			else
			{
				rankJdbc.insert(gameId, userID, rankNumber);
				result.put("result", true);
			}
		} 
		catch (JSONException e) {
			e.printStackTrace();
		}
		
		PrintWriter pw = response.getWriter();
		pw.write(result.toString());
		
	}

}
